<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="序列号" prop="serialNo">
        <el-input
          v-model="queryParams.serialNo"
          placeholder="请输入序列号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="工单号" prop="docNo">
        <el-input
          v-model="queryParams.docNo"
          placeholder="请输入工单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物料号" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入物料号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物料规格" prop="itemSpecification">
        <el-input
          v-model="queryParams.itemSpecification"
          placeholder="请输入物料规格"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="长度区间" prop="minQty" v-if="props.type == 'selectMaterial'">
        <el-input
          v-model="queryParams.minQty"
          placeholder="最小长度"
          clearable
          type="number"
          @keyup.enter="handleQuery"
          class="!w-100px"
        />
        —
        <el-input
          v-model="queryParams.maxQty"
          placeholder="最大长度"
          clearable
          @keyup.enter="handleQuery"
          type="number"
          class="!w-100px"
        />
      </el-form-item>
      <!-- <el-form-item label="材料描述" prop="itemDesc">
        <el-input
          v-model="queryParams.itemDesc"
          placeholder="请输入材料描述"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="材料图号" prop="drawingNo">
        <el-input
          v-model="queryParams.drawingNo"
          placeholder="请输入材料图号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入单位"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="物料类型" prop="materialType">
        <el-select
          v-model="queryParams.materialType"
          placeholder="请选择物料类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="sourceType">
        <el-select
          v-model="queryParams.sourceType"
          placeholder="请选择来源"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.OPTICORE_SOURCE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="数量" prop="qty">
        <el-input
          v-model="queryParams.qty"
          placeholder="请输入数量"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="入库时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          plain-->
        <!--          @click="openForm('create')"-->
        <!--          v-hasPermi="['opticore:material-inventor:create']"-->
        <!--        >-->
        <!--          <Icon icon="ep:plus" class="mr-5px" /> 新增-->
        <!--        </el-button>-->
        <el-button
          v-if="props.type != 'selectMaterial'"
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['opticore:material-inventor:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      highlight-current-row
      :show-overflow-tooltip="true"
    >
      <el-table-column label="编号" align="center" prop="id" v-if="false" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="序列号" align="center" prop="serialNo" />
      <el-table-column label="唯一标识" align="center" prop="warehouseNo" />
      <el-table-column label="批次号" align="center" prop="batchNo" />
      <el-table-column label="工单号" align="center" prop="docNo" />
      <el-table-column label="物料号" align="center" prop="itemCode" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="物料类型" align="center" prop="materialType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OPTICORE_MATE_TYPE" :value="scope.row.materialType" />
        </template>
      </el-table-column>
      <el-table-column label="物料单位" align="center" prop="unit" />
      <el-table-column label="物料规格" align="center" prop="itemSpecification" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="长度" align="center" prop="qty" />
      <!-- <el-table-column label="材料描述" align="center" prop="itemDesc" /> -->
      <el-table-column label="物料图号" align="center" prop="drawingNo" />
      <el-table-column label="来源" align="center" prop="sourceType">
        <template #default="{ row }">
          <div>{{ row.sourceType == 1 ? '中间库' : row.sourceType == 2 ? '仓库' : '' }}</div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="主图" align="center" prop="mainImage" /> -->
      <!-- <el-table-column label="状态" align="center" prop="status" /> -->
      <el-table-column
        label="入库时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            v-if="props.type == 'selectMaterial'"
            link
            type="primary"
            v-hasPermi="['opticore:material-inventor:update']"
          >
            <el-checkbox
              v-model="scope.row.selItem"
              label=""
              size="large"
              :disabled="scope.row.isAbled"
              @change="handleStockOut(scope.row)"
            />
          </el-button>

          <el-button
            v-else
            link
            type="primary"
            @click="openForm('query', scope.row)"
            v-hasPermi="['opticore:material-inventor:query']"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MaterialInventorform ref="formRef" @success="getList" />

  <!-- 出库对话框 -->

  <el-dialog v-model="stockOutDialogVisible" title="出库操作" width="400px">
    <el-form>
      <el-form-item label="物料号">
        <span>{{ currentStockRow?.itemCode }}</span>
      </el-form-item>
      <el-form-item label="物料名称">
        <span>{{ currentStockRow?.itemName }}</span>
      </el-form-item>
      <el-form-item label="出库数量" required>
        <el-input-number
          v-model="stockOutQty"
          :min="1"
          :max="currentStockRow?.qty || 0"
          :controls="false"
          placeholder="请输入出库数量"
        />
      </el-form-item>
      <el-form-item label="出库位置">
        <el-input v-model="stockOutLocation" placeholder="请输入出库位置" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="stockOutDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmStockOut()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MaterialInventorApi, MaterialInventorVO } from '@/api/opticore/materialinventor'
import MaterialInventorform from './MaterialInventorForm.vue'
import { install$11 } from 'echarts/types/dist/shared'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 中间库 列表 */
defineOptions({ name: 'MaterialInventor' })

const props = defineProps(['type', 'serialNo', 'itemCode', 'selmaxNum', 'warehouseNo'])
const emits = defineEmits(['selectItem'])

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MaterialInventorVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  serialNo: undefined,
  batchNo: undefined,
  docNo: undefined,
  itemCode: undefined,
  itemName: undefined,
  itemSpecification: undefined,
  itemDesc: undefined,
  drawingNo: undefined,
  sourceType: undefined,
  unit: undefined,
  materialType: undefined,
  brand: undefined,
  qty: undefined,
  location: undefined,
  mainImage: undefined,
  status: undefined,
  createTime: [],
  minQty: undefined,
  maxQty: undefined
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const stockOutDialogVisible = ref(false)
const stockOutQty = ref()
const stockOutLocation = ref()
const currentStockRow = ref<any>(null)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    if (props.type == 'selectMaterial') {
      queryParams.status = 0
    } else {
      queryParams.status = undefined
    }
    const data = await MaterialInventorApi.getMaterialViewPage(queryParams)

    data.list = data.list.map((item) => {
      if (
        item.serialNo == null || item.serialNo == ''
          ? item.warehouseNo == props.warehouseNo
          : item.serialNo == props.serialNo
      ) {
        // console.log(1111, item.qty, props.selmaxNum)
        console.log('warehouseNo', props.warehouseNo)
        console.log('serialNo', props.serialNo)
        return {
          ...item,
          selItem: true,
          isAbled: item.qty < props.selmaxNum ? true : false
        }
      }
      return {
        ...item,
        selItem: false,
        isAbled: item.qty < props.selmaxNum ? true : false
      }
    })

    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (queryParams.minQty > queryParams.maxQty) {
    message.info('物料最大长度不能小于最小长度')
    queryParams.maxQty = undefined

    return
  }
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.maxQty = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, row?: any) => {
  formRef.value.open(type, row)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MaterialInventorApi.deleteMaterialInventor(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MaterialInventorApi.exportMaterialInventor(queryParams)
    download.excel(data, '物料追溯.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleStockOut = (row: any) => {
  list.value = list.value.map((item) => {
    if (item.id == row.id) {
      // 切换选中状态
      return {
        ...item,
        selItem: item.selItem // 取反当前选中状态
      }
    }
    return {
      ...item,
      selItem: false // 保持单选特性，其他行取消选中
    }
  })

  // 根据当前选中状态传递参数
  if (row.selItem) {
    emits('selectItem', row)
  } else {
    emits('selectItem', null) // 取消选中时传递null
  }
}

const confirmStockOut = async () => {
  console.log(1)
  // 这里调用出库接口，传递 currentStockRow.value.id 和 stockOutQty.value

  // await MaterialInventorApi.updateMaterialInventor({ id: currentStockRow.value.id, qty: stockOutQty.value })
  // 1. 校验出库数量不能为空且为正整数
  if (!stockOutQty.value && stockOutQty.value <= 0) {
    message.error('出库数量必须大于0')
    return
  }
  // 2. 校验出库数量不能大于现有库存
  if (stockOutQty.value > currentStockRow.value.qty) {
    message.error('出库数量不能大于现有库存数量')
    return
  }

  const params = {
    ...currentStockRow.value,
    qty: currentStockRow.value.qty - stockOutQty.value, // 更新后的数量
    location: stockOutLocation.value
  }
  await MaterialInventorApi.updateMaterialInventor(params)
  console.log(stockOutQty.value)
  message.success('出库成功')

  stockOutDialogVisible.value = false
  getList()
}

/** 初始化 **/
onMounted(() => {
  queryParams.itemCode = props.itemCode
  getList()
})


watch(
  props, //监听选择来料的品号发生变化
  (val,old) => {
    queryParams.itemCode = props.itemCode
    getList()
  }
)


</script>
